<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div class="markdown-body">
        <style>
            .markdown-body {
                word-break: break-word;
                line-height: 1.75;
                font-weight: 400;
                font-size: 15px;
                overflow-x: hidden;
                color: #333
            }

            .markdown-body h1,
            .markdown-body h2,
            .markdown-body h3,
            .markdown-body h4,
            .markdown-body h5,
            .markdown-body h6 {
                line-height: 1.5;
                margin-top: 35px;
                margin-bottom: 10px;
                padding-bottom: 5px
            }

            .markdown-body h1 {
                font-size: 30px;
                margin-bottom: 5px
            }

            .markdown-body h2 {
                padding-bottom: 12px;
                font-size: 24px;
                border-bottom: 1px solid #ececec
            }

            .markdown-body h3 {
                font-size: 18px;
                padding-bottom: 0
            }

            .markdown-body h4 {
                font-size: 16px
            }

            .markdown-body h5 {
                font-size: 15px
            }

            .markdown-body h6 {
                margin-top: 5px
            }

            .markdown-body p {
                line-height: inherit;
                margin-top: 22px;
                margin-bottom: 22px
            }

            .markdown-body img {
                max-width: 100%
            }

            .markdown-body hr {
                border: none;
                border-top: 1px solid #ddd;
                margin-top: 32px;
                margin-bottom: 32px
            }

            .markdown-body code {
                word-break: break-word;
                border-radius: 2px;
                overflow-x: auto;
                background-color: #fff5f5;
                color: #ff502c;
                font-size: .87em;
                padding: .065em .4em
            }

            .markdown-body code,
            .markdown-body pre {
                font-family: Menlo, Monaco, Consolas, Courier New, monospace
            }

            .markdown-body pre {
                overflow: auto;
                position: relative;
                line-height: 1.75
            }

            .markdown-body pre>code {
                font-size: 12px;
                padding: 15px 12px;
                margin: 0;
                word-break: normal;
                display: block;
                overflow-x: auto;
                color: #333;
                background: #f8f8f8
            }

            .markdown-body a {
                text-decoration: none;
                color: #0269c8;
                border-bottom: 1px solid #d1e9ff
            }

            .markdown-body a:active,
            .markdown-body a:hover {
                color: #275b8c
            }

            .markdown-body table {
                display: inline-block !important;
                font-size: 12px;
                width: auto;
                max-width: 100%;
                overflow: auto;
                border: 1px solid #f6f6f6
            }

            .markdown-body thead {
                background: #f6f6f6;
                color: #000;
                text-align: left
            }

            .markdown-body tr:nth-child(2n) {
                background-color: #fcfcfc
            }

            .markdown-body td,
            .markdown-body th {
                padding: 12px 7px;
                line-height: 24px
            }

            .markdown-body td {
                min-width: 120px
            }

            .markdown-body blockquote {
                color: #666;
                padding: 1px 23px;
                margin: 22px 0;
                border-left: 4px solid #cbcbcb;
                background-color: #f8f8f8
            }

            .markdown-body blockquote:after {
                display: block;
                content: ""
            }

            .markdown-body blockquote>p {
                margin: 10px 0
            }

            .markdown-body ol,
            .markdown-body ul {
                padding-left: 28px
            }

            .markdown-body ol li,
            .markdown-body ul li {
                margin-bottom: 0;
                list-style: inherit
            }

            .markdown-body ol li .task-list-item,
            .markdown-body ul li .task-list-item {
                list-style: none
            }

            .markdown-body ol li .task-list-item ol,
            .markdown-body ol li .task-list-item ul,
            .markdown-body ul li .task-list-item ol,
            .markdown-body ul li .task-list-item ul {
                margin-top: 0
            }

            .markdown-body ol ol,
            .markdown-body ol ul,
            .markdown-body ul ol,
            .markdown-body ul ul {
                margin-top: 3px
            }

            .markdown-body ol li {
                padding-left: 6px
            }

            .markdown-body .contains-task-list {
                padding-left: 0
            }

            .markdown-body .task-list-item {
                list-style: none
            }

            @media (max-width:720px) {
                .markdown-body h1 {
                    font-size: 24px
                }

                .markdown-body h2 {
                    font-size: 20px
                }

                .markdown-body h3 {
                    font-size: 18px
                }
            }
        </style>
        <blockquote>
            <p>Base64 是一组相似的二进制到文本（binary-to-text）的编码规则，使得二进制数据在解释成 radix-64 的表现形式后能够用 ASCII 字符串的格式表示出来。Base64 这个词出自一种
                MIME 数据传输编码。</p>
        </blockquote>
        <h2 data-id="heading-0">浏览器</h2>
        <p>现代浏览器原生支持<code>base64</code>的编解码，在控制台和<code>js worker</code>中都可使用，其提供了2个方法：<code>atob()</code>
            <code>btoa()</code>,分别用于解码和编码.
        </p>
        <h3 data-id="heading-1">btoa()</h3>
        <p>从 <code>String</code> 对象中创建一个<code>base-64</code>编码的<code>ASCII</code>字符串，其中字符串中的每个字符都被视为一个二进制数据字节。</p>
        <blockquote>
            <p>由于这个函数将每个字符视为二进制数据的字节，而不管实际组成字符的字节数是多少，所以如果任何字符的码位超出 0x00 ~ 0xFF 这个范围，则会引发 InvalidCharacterError 异常。请参阅
                Unicode_字符串 ，该示例演示如何编码含有码位超出 0x00 ~ 0xFF 范围的字符的字符串。</p>
        </blockquote>
        <p>因此，该函数只能将<code>ascll</code>字符串编码成<code>base64</code>格式，对于<code>ascll</code>以外的字符串则会报错</p>
        <p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a78e10e3c25649299525b457621b8d9e~tplv-k3u1fbpfcp-watermark.awebp"
                alt="浏览器和node中使用base64编解码" loading="lazy" class="medium-zoom-image"></p>
        <p>错误提示要编码的字符中包含了<code>latin1</code>编码以外的字符，这些字符是不能被编码的。</p>
        <p><code>latin1</code>: <code>Latin-1</code> 代表 ISO-8859-1。 此字符编码仅支持从 <code>U+0000</code> 到 <code>U+00FF</code>
            的 <code>Unicode</code> 字符。 每个字符使用单个字节进行编码。 超出该范围的字符会被截断，并映射成该范围内的字符。</p>
        <p>解决方法是将字符串中的非<code>ascll</code>字符进行转义，然后再进行编码</p>
        <pre><code class="hljs language-js copyable" lang="js"><span class="hljs-comment">// unicode to base64</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">utoa</span>(<span class="hljs-params">str</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">window</span>.btoa(<span class="hljs-built_in">unescape</span>(<span class="hljs-built_in">encodeURIComponent</span>(str)));
}
<span class="copy-code-btn">复制代码</span></code></pre>
        <p>上述代码来源于MDN文档<a
                href="https://link.juejin.cn?target=https%3A%2F%2Fdeveloper.mozilla.org%2Fzh-CN%2Fdocs%2FWeb%2FAPI%2FWindowBase64%2Fbtoa%23Unicode_%25E5%25AD%2597%25E7%25AC%25A6%25E4%25B8%25B2"
                target="_blank" rel="nofollow noopener noreferrer"
                title="https://developer.mozilla.org/zh-CN/docs/Web/API/WindowBase64/btoa#Unicode_%E5%AD%97%E7%AC%A6%E4%B8%B2"
                ref="nofollow noopener noreferrer">WindowOrWorkerGlobalScope.btoa()</a></p>
        <p><code>encodeURIComponent</code>用于将字符串中非<code>ascll</code>字符转义成格式为"%加字符的<code>ASCII</code>码"的十六进制转义序列,常用于<code>URI</code>的处理。
        </p>
        <p>处理后的字符串完全由ascll字符组成，再由<code>unescape()</code>将其中的十六进制转义序列转换为其表示的字符,最后再由<code>btoa()</code>编码成<code>base64</code>,不过这里的<code>unescape()</code>是非必要的，一方面该方法已被web标准弃用，二是经过转义的字符串已经能够被<code>btoa()</code>编码。
        </p>
        <pre><code class="hljs language-js copyable" lang="js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">utoa</span>(<span class="hljs-params">str</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">window</span>.btoa(<span class="hljs-built_in">encodeURIComponent</span>(str));
}
<span class="copy-code-btn">复制代码</span></code></pre>
        <p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/3d89359b9d3b4588b4df3240560e017e~tplv-k3u1fbpfcp-watermark.awebp"
                alt="浏览器和node中使用base64编解码-2" loading="lazy" class="medium-zoom-image"></p>
        <pre><code class="hljs language-js copyable" lang="js"><span class="hljs-comment">// unicode to base64 by </span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">utoa</span>(<span class="hljs-params">str</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">window</span>.btoa(<span class="hljs-built_in">unescape</span>(<span class="hljs-built_in">encodeURIComponent</span>(str)));
}
<span class="hljs-comment">// base64 to unicode</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">atou</span>(<span class="hljs-params">str</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">decodeURIComponent</span>(<span class="hljs-built_in">escape</span>(<span class="hljs-built_in">window</span>.atob(str)));
}
<span class="copy-code-btn">复制代码</span></code></pre>
        <h3 data-id="heading-2">atob()</h3>
        <p>与上面同理，直接使用<code>atob()</code>转换一个不是全由<code>ascll</code>字符组成的字符串编码成的<code>base64</code>字符串时，会报与上述同样的错误。</p>
        <p><code>MDN</code>文档<a
                href="https://link.juejin.cn?target=https%3A%2F%2Fdeveloper.mozilla.org%2Fzh-CN%2Fdocs%2FWeb%2FAPI%2FWindowBase64%2Fbtoa%23Unicode_%25E5%25AD%2597%25E7%25AC%25A6%25E4%25B8%25B2"
                target="_blank" rel="nofollow noopener noreferrer"
                title="https://developer.mozilla.org/zh-CN/docs/Web/API/WindowBase64/btoa#Unicode_%E5%AD%97%E7%AC%A6%E4%B8%B2"
                ref="nofollow noopener noreferrer">WindowOrWorkerGlobalScope.btoa()</a>的方法</p>
        <pre><code class="hljs language-js copyable" lang="js"><span class="hljs-comment">// base64 to unicode</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">atou</span>(<span class="hljs-params">str</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">decodeURIComponent</span>(<span class="hljs-built_in">escape</span>(<span class="hljs-built_in">window</span>.atob(str)));
}
<span class="copy-code-btn">复制代码</span></code></pre>
        <p><code>escape()</code>是非必要的</p>
        <pre><code class="hljs language-js copyable" lang="js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">atou</span>(<span class="hljs-params">str</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">decodeURIComponent</span>(<span class="hljs-built_in">window</span>.atob(str));
}
<span class="copy-code-btn">复制代码</span></code></pre>
        <h3 data-id="heading-3">Polyfill</h3>
        <p>有不少PC项目还需要兼容IE9以下版本，所以，我们可以专门针对这些浏览器再引入一段<code>ployfill</code>脚本或者一个<code>JS</code>文件即可。</p>
        <p><a href="https://link.juejin.cn?target=https%3A%2F%2Fgithub.com%2FMaxArt2501%2Fbase64-js%2Fblob%2Fmaster%2Fbase64.js"
                target="_blank" rel="nofollow noopener noreferrer"
                title="https://github.com/MaxArt2501/base64-js/blob/master/base64.js"
                ref="nofollow noopener noreferrer">github.com/MaxArt2501/…</a></p>
        <p>另一个<code>ployfill</code>实现</p>
        <p><a href="https://link.juejin.cn?target=https%3A%2F%2Fgithub.com%2Fdavidchambers%2FBase64.js%2Fblob%2Fmaster%2Fbase64.js"
                target="_blank" rel="nofollow noopener noreferrer"
                title="https://github.com/davidchambers/Base64.js/blob/master/base64.js"
                ref="nofollow noopener noreferrer">github.com/davidchambe…</a></p>
        <pre><code class="hljs language-js copyable" lang="js"><span class="hljs-comment">// Polyfill from  https://github.com/MaxArt2501/base64-js/blob/master/base64.js</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// base64 character set, plus padding character (=)</span>
    <span class="hljs-keyword">var</span> b64 = <span class="hljs-string">"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="</span>,

        <span class="hljs-comment">// Regular expression to check formal correctness of base64 encoded strings</span>
        b64re = <span class="hljs-regexp">/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/</span>;

    <span class="hljs-built_in">window</span>.btoa = <span class="hljs-built_in">window</span>.btoa || <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">string</span>) </span>{
        string = <span class="hljs-built_in">String</span>(string);
        <span class="hljs-keyword">var</span> bitmap, a, b, c,
            result = <span class="hljs-string">""</span>,
            i = <span class="hljs-number">0</span>,
            rest = string.length % <span class="hljs-number">3</span>; <span class="hljs-comment">// To determine the final padding</span>

        <span class="hljs-keyword">for</span> (; i &lt; string.length;) {
            <span class="hljs-keyword">if</span> ((a = string.charCodeAt(i++)) &gt; <span class="hljs-number">255</span> ||
                (b = string.charCodeAt(i++)) &gt; <span class="hljs-number">255</span> ||
                (c = string.charCodeAt(i++)) &gt; <span class="hljs-number">255</span>)
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">"Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range."</span>);

            bitmap = (a &lt;&lt; <span class="hljs-number">16</span>) | (b &lt;&lt; <span class="hljs-number">8</span>) | c;
            result += b64.charAt(bitmap &gt;&gt; <span class="hljs-number">18</span> &amp; <span class="hljs-number">63</span>) + b64.charAt(bitmap &gt;&gt; <span class="hljs-number">12</span> &amp; <span class="hljs-number">63</span>) +
                b64.charAt(bitmap &gt;&gt; <span class="hljs-number">6</span> &amp; <span class="hljs-number">63</span>) + b64.charAt(bitmap &amp; <span class="hljs-number">63</span>);
        }

        <span class="hljs-comment">// If there's need of padding, replace the last 'A's with equal signs</span>
        <span class="hljs-keyword">return</span> rest ? result.slice(<span class="hljs-number">0</span>, rest - <span class="hljs-number">3</span>) + <span class="hljs-string">"==="</span>.substring(rest) : result;
    };

    <span class="hljs-built_in">window</span>.atob = <span class="hljs-built_in">window</span>.atob || <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">string</span>) </span>{
        <span class="hljs-comment">// atob can work with strings with whitespaces, even inside the encoded part,</span>
        <span class="hljs-comment">// but only \t, \n, \f, \r and ' ', which can be stripped.</span>
        string = <span class="hljs-built_in">String</span>(string).replace(<span class="hljs-regexp">/[\t\n\f\r ]+/g</span>, <span class="hljs-string">""</span>);
        <span class="hljs-keyword">if</span> (!b64re.test(string))
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">TypeError</span>(<span class="hljs-string">"Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded."</span>);

        <span class="hljs-comment">// Adding the padding if missing, for semplicity</span>
        string += <span class="hljs-string">"=="</span>.slice(<span class="hljs-number">2</span> - (string.length &amp; <span class="hljs-number">3</span>));
        <span class="hljs-keyword">var</span> bitmap, result = <span class="hljs-string">""</span>,
            r1, r2, i = <span class="hljs-number">0</span>;
        <span class="hljs-keyword">for</span> (; i &lt; string.length;) {
            bitmap = b64.indexOf(string.charAt(i++)) &lt;&lt; <span class="hljs-number">18</span> | b64.indexOf(string.charAt(i++)) &lt;&lt; <span class="hljs-number">12</span> |
                (r1 = b64.indexOf(string.charAt(i++))) &lt;&lt; <span class="hljs-number">6</span> | (r2 = b64.indexOf(string.charAt(i++)));

            result += r1 === <span class="hljs-number">64</span> ? <span class="hljs-built_in">String</span>.fromCharCode(bitmap &gt;&gt; <span class="hljs-number">16</span> &amp; <span class="hljs-number">255</span>) :
                r2 === <span class="hljs-number">64</span> ? <span class="hljs-built_in">String</span>.fromCharCode(bitmap &gt;&gt; <span class="hljs-number">16</span> &amp; <span class="hljs-number">255</span>, bitmap &gt;&gt; <span class="hljs-number">8</span> &amp; <span class="hljs-number">255</span>) :
                <span class="hljs-built_in">String</span>.fromCharCode(bitmap &gt;&gt; <span class="hljs-number">16</span> &amp; <span class="hljs-number">255</span>, bitmap &gt;&gt; <span class="hljs-number">8</span> &amp; <span class="hljs-number">255</span>, bitmap &amp; <span class="hljs-number">255</span>);
        }
        <span class="hljs-keyword">return</span> result;
    };
})()
<span class="copy-code-btn">复制代码</span></code></pre>
        <h3 data-id="heading-4">类型化数组转base64</h3>
        <p>有时候后端传给我们一个二进制流的文件资源，我们需要使用一个类型化数组来进行存储和读取。</p>
        <p><code>ArrayBuffer</code>我们叫它类型化数组，它的诞生就是为了解决一个问题：操作二进制数据。</p>
        <p>只由<code>0</code>和<code>1</code>组成的二进制数据往往是非常巨大的，上千个字节可以说司空见惯，传统的<code>Array</code>这时候处理起二进制数据起来就显得非常低效，所以<code>ArrayBuffer</code>出现了，它作为一块专用的内存区域存放在栈中，取数据非常快。
        </p>
        <p>我们现在通过<code>new ArrayBuffer(10)</code>初始化一个buffer实例，看看会得到什么。</p>
        <pre><code class="hljs language-js copyable" lang="js"><span class="hljs-keyword">let</span> buffer = <span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>(<span class="hljs-number">10</span>);
<span class="hljs-built_in">console</span>.log(buffer);

<span class="hljs-function"><span class="hljs-title">ArrayBuffer</span>(<span class="hljs-params"><span class="hljs-number">10</span></span>)</span> {}
[[<span class="hljs-built_in">Int8Array</span>]]: <span class="hljs-built_in">Int8Array</span>(<span class="hljs-number">10</span>) [<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>]
[[<span class="hljs-built_in">Int16Array</span>]]: <span class="hljs-built_in">Int16Array</span>(<span class="hljs-number">5</span>) [<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>]
[[<span class="hljs-built_in">Uint8Array</span>]]: <span class="hljs-built_in">Uint8Array</span>(<span class="hljs-number">10</span>) [<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>]
<span class="hljs-attr">byteLength</span>: <span class="hljs-number">10</span>
<span class="hljs-attr">__proto__</span>: <span class="hljs-built_in">ArrayBuffer</span>
<span class="copy-code-btn">复制代码</span></code></pre>
        <p>可以看到在ArrayBuffer中，主要存放了几个<strong>视图</strong>，<code>Int8Array</code>表示<code>8</code>位有符号整数数组，<code>Int16Array</code>表示<code>16</code>位有符号整数数组，<code>Uint8Array</code>则表示<code>8</code>位无符号整数数组。
        </p>
        <p>当然，如果比如说我们想取出<code>Int8Array</code>这个数组来，是不能直接通过<code>buffer.Int8Array</code>来取的。这是因为<code>ArrayBuffer</code>不能直接通过下标去读写,我们需要构造相关类型数组实例。
        </p>
        <pre><code class="hljs language-js copyable" lang="js"><span class="hljs-keyword">const</span> myUint8Array = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Uint8Array</span>(buffer)
<span class="copy-code-btn">复制代码</span></code></pre>
        <p>得到数组值后，怎样才能将其转换成<code>base64</code>呢?
            很简单，使用<code>String.fromCharCode</code>这个函数，它接受的参数为一堆代码单元序列，输出一个普通字符串。而我们刚刚得到的类型化数组，里面存放的正是代码单元。</p>
        <pre><code class="hljs language-js copyable" lang="js"><span class="hljs-keyword">const</span> myStr = <span class="hljs-built_in">String</span>.fromCharCode(...myUint8Array)
<span class="copy-code-btn">复制代码</span></code></pre>
        <p>现在类型数组里的值已经被全部转换成字符串了，我们再使用<code>btoa()</code>将其编码成<code>base64</code>字符串</p>
        <h2 data-id="heading-5">node</h2>
        <p><code>node</code>环境中虽然没有提供专门方法去进行<code>base64</code>的编解码，但是我们能利用<a
                href="https://link.juejin.cn?target=http%3A%2F%2Fnodejs.cn%2Fapi%2Fbuffer.html%23buffer_buf_tostring_encoding_start_end"
                target="_blank" rel="nofollow noopener noreferrer"
                title="http://nodejs.cn/api/buffer.html#buffer_buf_tostring_encoding_start_end"
                ref="nofollow noopener noreferrer">buffer.toString()</a>很轻松的完成，不仅仅是处理字符串，处理文件也非常方便。</p>
        <h3 data-id="heading-6">处理字符串</h3>
        <pre><code class="hljs language-js copyable" lang="js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stringToBase64</span>(<span class="hljs-params">str</span>)</span>{
    <span class="hljs-keyword">let</span> base64Str = Buffer.from(str).toString(<span class="hljs-string">'base64'</span>)
    <span class="hljs-keyword">return</span> base64Str;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">base64ToString</span>(<span class="hljs-params">base64Str</span>)</span>{
    <span class="hljs-keyword">let</span> str = Buffer.from(base64Str,<span class="hljs-string">'base64'</span>).toString()
    <span class="hljs-keyword">return</span> str
}
<span class="copy-code-btn">复制代码</span></code></pre>
        <h3 data-id="heading-7">处理文件</h3>
        <p>举个栗子</p>
        <p>对一幅图片进行<code>base64</code>编解码</p>
        <pre><code class="hljs language-js copyable" lang="js"><span class="hljs-comment">//编码</span>
<span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>)
<span class="hljs-keyword">const</span> fileToBase64  = fs.readFileSync(<span class="hljs-string">'./img.png'</span>)
<span class="hljs-built_in">console</span>.log(fileToBase64.toString(<span class="hljs-string">'base64'</span>))

<span class="hljs-comment">//输出</span>
iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAAgAElEQVR4Xuy9CZQdZ3Uu+tVcdeah5251t8bWZEuyJGxjecJDGHMJYEISwiPAu7DyXt66YSUvyc3wlEByIXkk910ePCC5gSQ3IYlJwg0EG4ONsS3Pkm1Jlq1Z6kE9nXmqU/Nbe1cdWZiEaAqms+p4tVtSV9X5z66/vt7Dt78tIH7FFogtEFtghVhAWCHrjJcZWyC2QGwBxIAVb4LYArEFVowFYsBaMbcqXmhsgdgCMWDFeyC2QGyBFWOBGLBWzK2KFxpbILZADFjxHogtEFtgxVggBqwVc6vihcYWiC0QA1a8B2ILxBZYMRaIAWvF3Kp4obEFYgvEgBXvgdgCsQVWjAViwFoxtypeaGyB2AIxYMV7ILZAbIEVY4EYsFbMrYoXGlsgtkAMWPEeiC0QW2DFWCAGrBVzq+KFxhaILRADVrwHYgvEFlgxFogBa8XcqnihsQViC8SAFe...

<span class="hljs-comment">//解码</span>
<span class="hljs-keyword">const</span> base64Tofile = Buffer.from(fileToBase64.toString(<span class="hljs-string">'base64'</span>),<span class="hljs-string">'base64'</span>)
<span class="hljs-comment">//输出为img2.png</span>
fs.writeFileSync(<span class="hljs-string">'img2.png'</span>, base64Tofile);
<span class="copy-code-btn">复制代码</span></code></pre>
        <p>编码后的文件要能被浏览器识别，必须根据其
            <code>MIME type</code>加上相应类型的前缀，如png图片:<code>data:image/png;base64,</code>，<code>txt</code>文本:<code>data:text/plain;base64,</code>
        </p>
        <h2 data-id="heading-8">js-base64库</h2>
        <p><a href="https://link.juejin.cn?target=https%3A%2F%2Fgithub.com%2Fdankogai%2Fjs-base64" target="_blank"
                rel="nofollow noopener noreferrer" title="https://github.com/dankogai/js-base64"
                ref="nofollow noopener noreferrer">github.com/dankogai/js…</a></p>
        <p>详情请看github文档，使用起来也非常方便</p>
        <style>
            .markdown-body pre,
            .markdown-body pre>code.hljs {
                color: #333;
                background: #f8f8f8
            }

            .hljs-comment,
            .hljs-quote {
                color: #998;
                font-style: italic
            }

            .hljs-keyword,
            .hljs-selector-tag,
            .hljs-subst {
                color: #333;
                font-weight: 700
            }

            .hljs-literal,
            .hljs-number,
            .hljs-tag .hljs-attr,
            .hljs-template-variable,
            .hljs-variable {
                color: teal
            }

            .hljs-doctag,
            .hljs-string {
                color: #d14
            }

            .hljs-section,
            .hljs-selector-id,
            .hljs-title {
                color: #900;
                font-weight: 700
            }

            .hljs-subst {
                font-weight: 400
            }

            .hljs-class .hljs-title,
            .hljs-type {
                color: #458;
                font-weight: 700
            }

            .hljs-attribute,
            .hljs-name,
            .hljs-tag {
                color: navy;
                font-weight: 400
            }

            .hljs-link,
            .hljs-regexp {
                color: #009926
            }

            .hljs-bullet,
            .hljs-symbol {
                color: #990073
            }

            .hljs-built_in,
            .hljs-builtin-name {
                color: #0086b3
            }

            .hljs-meta {
                color: #999;
                font-weight: 700
            }

            .hljs-deletion {
                background: #fdd
            }

            .hljs-addition {
                background: #dfd
            }

            .hljs-emphasis {
                font-style: italic
            }

            .hljs-strong {
                font-weight: 700
            }
        </style>
    </div>
    <script src="./index.js" type="module" defer></script>
</body>

</html>